package com.yange.accountbook.ui

import android.app.DatePickerDialog
import android.graphics.Color
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.charts.PieChart
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.*
import com.github.mikephil.charting.formatter.PercentFormatter
import com.github.mikephil.charting.formatter.ValueFormatter
import com.github.mikephil.charting.utils.ColorTemplate
import com.yange.accountbook.R
import com.yange.accountbook.databinding.ReportActivityLayoutBinding
import com.yange.accountbook.entity.AccountDetailEntity
import com.yange.accountbook.entity.ReportInfoEntity
import com.yange.accountbook.net.Api
import com.yange.accountbook.net.BaseResponse
import com.yange.accountbook.net.api.RetrofitClient
import com.yange.accountbook.net.observable.RecObserver
import com.yange.accountbook.utils.StringUtils
import com.yange.accountbook.utils.UserDao
import com.yange.accountbook.utils.image.loadCircleImg
import com.yange.accountbook.utils.showToast
import java.math.BigDecimal
import java.util.*
import java.util.stream.Collectors


class ReportFragment : BaseFragment<ReportActivityLayoutBinding>() {


    var year = 2022
    var month = 11
    var day = 1
    var colors = arrayListOf<Int>()

    lateinit var dialog: DatePickerDialog
    lateinit var monOutTop: PieChart
    lateinit var yearSave: LineChart
    lateinit var monOutAdapter: MonOutAdapter

    override fun initView() {

        monOutTop = binding.ctMonOutTop
        yearSave = binding.ctYearSave

        colors.addAll(ColorTemplate.COLORFUL_COLORS.toList())
        colors.addAll(ColorTemplate.JOYFUL_COLORS.toList())

        monOutAdapter = MonOutAdapter()
        binding.dataList.layoutManager = LinearLayoutManager(context)
        binding.dataList.adapter = monOutAdapter

        initListener()
        initDate()
        refresh()


    }

    override fun initData() {}

    fun refresh() {
        initTotalMoney()
        initAccountOut()
        initYearSave()
    }

    class MonOutAdapter :
        BaseQuickAdapter<ReportInfoEntity, BaseViewHolder>(R.layout.report_list_item_layout) {
        override fun convert(holder: BaseViewHolder, item: ReportInfoEntity) {
            holder.setText(R.id.tv_book_name, item.name + " " + item.percent + "%")
            holder.setText(R.id.tv_money, "￥" + item.money.toString())
            var image = holder.getView<ImageView>(R.id.iv_book_icon)
            context.loadCircleImg(image, item.icon)
        }
    }

    fun initAccountOut() {
        RetrofitClient.getInstance().invokePostBody(
            activity, Api.REPORT_LIST, mapOf(
                "queryType" to "ACCOUNT",
                "type" to "OUT",
                "year" to year,
                "mon" to (month + 1)
            )
        )
            .subscribe(object :
                RecObserver<BaseResponse<List<ReportInfoEntity>>>(activity, false, false) {
                override fun onSuccess(t: BaseResponse<List<ReportInfoEntity>>?) {

                    buildMonOutTop(t!!.data)
                    monOutAdapter.setNewInstance(t?.data as MutableList<ReportInfoEntity>?)
                }

                override fun onFail(msg: String, code: Int) {
                    showToast(msg)
                }
            })
    }

    fun initYearSave() {
        RetrofitClient.getInstance().invokePostBody(
            activity, Api.REPORT_LIST, mapOf(
                "queryType" to "SAVE",
                "year" to year
            )
        )
            .subscribe(object :
                RecObserver<BaseResponse<List<ReportInfoEntity>>>(activity, false, false) {
                override fun onSuccess(t: BaseResponse<List<ReportInfoEntity>>?) {
                    buildYearSave(t!!.data)
                }

                override fun onFail(msg: String, code: Int) {
                    showToast(msg)
                }
            })
    }

    fun buildYearSave(data: List<ReportInfoEntity>) {

        //背景颜色
        yearSave.setBackgroundColor(Color.WHITE)

        //设置动画效果
        yearSave.animateY(1000, Easing.Linear)
        yearSave.animateX(1000, Easing.Linear)
        yearSave.setExtraOffsets(20f, 20f, 20f, 20f)


        //获取图表右下角的描述性文字，setEnable（）默认为true
        yearSave.getDescription().setEnabled(false);


        /***XY轴的设置 */
        //X轴设置显示位置在底部
        var xAxis = yearSave.xAxis
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM)
        xAxis.setAxisMinimum(0f)
        xAxis.setGranularity(1f)
        xAxis.setDrawGridLines(false)
        xAxis.setLabelCount(data.size)
        var xNames = data.stream().map { it.name }.collect(Collectors.toList());
        xAxis.valueFormatter = object : ValueFormatter() {
            override fun getFormattedValue(value: Float): String {
                if (value < 0 || value.toInt() > xNames.size - 1) {
                    return ""
                }
                return xNames.get(value.toInt())
            }
        }
        // 设置y轴，y轴有两条，分别为左和右
        val yAxis = yearSave.axisRight
        yAxis.isEnabled = false // 不显示右边的y轴
        yAxis.setDrawAxisLine(false)
        yearSave.axisLeft.setDrawAxisLine(false)

        var entrys = arrayListOf<Entry>()
        for (i in data.indices) {
            entrys.add(Entry(i.toFloat(), data[i].money.toFloat()))
        }

        var dataSet = LineDataSet(entrys, "")
        dataSet.setDrawValues(true)

        yearSave.data = LineData(dataSet)
        yearSave.invalidate()

    }

    fun buildMonOutTop(data: List<ReportInfoEntity>) {

        monOutTop.getDescription().setEnabled(false)//设置描述
        monOutTop.setDragDecelerationFrictionCoef(0.95f)//设置阻尼系数,范围在[0,1]之间,越小饼状图转动越困难
        monOutTop.setRotationEnabled(true)//设置饼状图是否可以旋转(默认为true)
        monOutTop.setHighlightPerTapEnabled(true)//设置旋转的时候点中的tab是否高亮(默认为true)
        monOutTop.setDrawEntryLabels(false)


        val l: Legend = monOutTop.getLegend()
        l.verticalAlignment = Legend.LegendVerticalAlignment.CENTER
        l.horizontalAlignment = Legend.LegendHorizontalAlignment.LEFT
        l.orientation = Legend.LegendOrientation.VERTICAL
        l.setDrawInside(false)
        l.xEntrySpace = 7f
        l.yEntrySpace = 0f
        l.yOffset = 0f

        var top = arrayListOf<ReportInfoEntity>()
        if (data.size < 5) {
            top.addAll(data)
        } else {
            top.addAll(data.subList(0, 4))
            var otherMoney =
                data.subList(4, data.size - 1).stream().map { it.money }.reduce(BigDecimal::add)
                    .get()
            var otherPercent =
                data.subList(4, data.size - 1).stream().map { it.percent }.reduce(Float::plus).get()
            top.add(ReportInfoEntity("其它", otherMoney, otherPercent, ""))
        }
        var list = top.stream()
            .map { PieEntry(it.money.toFloat(), it.name + "(" + it.percent + "%）") }
            .collect(Collectors.toList())
        var dataSet = PieDataSet(list, "")
        dataSet.setSliceSpace(3f)
        dataSet.setSelectionShift(5f)

        dataSet.setColors(colors)

        var data = PieData(dataSet)
        data.setValueFormatter(PercentFormatter())
        data.setValueTextSize(12f)
        data.setValueTextColor(Color.BLACK)

        monOutTop.setData(data)
        monOutTop.invalidate()
    }


    fun initDate() {
        val calendar: Calendar = Calendar.getInstance()
        buildDate(
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        )
    }

    fun buildDate(year1: Int, month1: Int, day1: Int) {

        month = month1
        year = year1
        day = day1
        if (UserDao.getUserInfo().periodStatus && day1 < UserDao.getUserInfo().periodDay) {
            month = month1 - 1
            if (month < 0) {
                month = 11
                year = year1 - 1
            }
        }
        binding.tvYear.text = year.toString() + "年"
        binding.tvMouth.text = (month + 1).toString() + "月"
    }

    fun initListener() {
        binding.layoutDate.setOnClickListener {
            dialog = DatePickerDialog(
                requireContext(),
                { p0, year1, month1, day1 ->
                    buildDate(year1, month1, day1)
                    refresh()
                },
                year,
                month,
                day
            )

            dialog.show()
        }
        //新增明细
        binding.titleBar.tvForward?.setOnClickListener {
            refresh()
        }
    }

    fun initTotalMoney() {

        RetrofitClient.getInstance().invokePostBody(
            activity, Api.REPORT_MON_MONEY, mapOf(
                "year" to year,
                "mon" to (month + 1)
            )
        ).subscribe(object :
            RecObserver<BaseResponse<AccountDetailEntity>>(activity, false, false) {
            override fun onSuccess(t: BaseResponse<AccountDetailEntity>?) {
                binding.tvOut.text = "￥" + StringUtils.getNoMoreThanTwoDigits(t?.data?.outMoney!!)
                binding.tvIn.text = "￥" + StringUtils.getNoMoreThanTwoDigits(t?.data?.inMoney!!)
            }

            override fun onFail(msg: String, code: Int) {
            }
        })
    }

}